export default (): {
  payOrder: (
    orderInfo: string | AnyObject,
    config?: Record<string, unknown>
  ) => Promise<boolean>;
  cancelMergeOrder: (
    outMergeNo: string,
    list: OrderDetail[],
    recipientInfo: RecipientInfo,
    merchantList: OrderMerchantVO[],
    remarkMap: Map<string, string>
  ) => Promise<void>;
} => {
  const payOrder = async (
    orderInfo: string | AnyObject,
    config: Record<string, unknown> = {}
  ) => {
    const provider = await getProvider();
    if (!provider) return false;
    const paymentResult = await requestPayment(provider, orderInfo, config);
    return paymentResult;
  };

  /** 获取支付权限 */
  const getProvider = async () => {
    const provider = await new Promise<PaymentProvider | undefined>(
      (resolve) => {
        uni.getProvider({
          service: 'payment',
          success: (result) => {
            resolve(result.provider?.[0] as PaymentProvider);
          },
          fail: () => resolve(undefined)
        });
      }
    );
    if (!provider) {
      await uni.showModal({ title: '支付授权失败', showCancel: false });
    } else {
      return provider;
    }
  };

  /** 拉起支付 */
  const requestPayment = async (
    provider: PaymentProvider,
    orderInfo: string | AnyObject,
    config: Record<string, unknown>
  ) => {
    const paymentResult = await new Promise<boolean>((resolve) => {
      // #ifdef MP-ALIPAY
      uni.requestPayment({
        provider,
        orderInfo,
        ...config,
        success: (res) => {
          console.log('拉起支付成功', res);
          resolve(res.resultCode === '9000');
        },
        fail: (error) => {
          console.log('拉起支付失败：', error);
          resolve(false);
        }
      });
      // #endif
      // #ifdef MP-WEIXIN
      if (typeof orderInfo === 'string') {
        console.log('拉起支付失败：参数类型错误');
        resolve(false);
      } else {
        uni.requestPayment({
          provider,
          orderInfo: '',
          timeStamp: orderInfo.timeStamp,
          nonceStr: orderInfo.nonceStr,
          package: orderInfo.package,
          signType: orderInfo.signType,
          paySign: orderInfo.paySign,
          ...config,
          success: (res) => {
            console.log('拉起支付成功', res);
            resolve(res?.errMsg?.includes('ok'));
          },
          fail: (error) => {
            console.log('拉起支付失败：', error);
            resolve(false);
          }
        });
      }
      // #endif
    });
    return paymentResult;
  };

  /** 取消联合支付订单  */
  const cancelMergeOrder = async (
    outMergeNo: string,
    list: OrderDetail[],
    recipientInfo: RecipientInfo,
    merchantList: OrderMerchantVO[],
    remarkMap: Map<string, string>
  ) => {
    uni.showLoading({ mask: true });
    const cancelResult = await cancelOrder(outMergeNo);
    if (!cancelResult) return;
    for (let i = 0; i < merchantList.length; i += 1) {
      const merchant = merchantList[i];
      const trialList = await getTrialList(recipientInfo, merchant);
      if (!trialList || trialList.length !== 1) return;
      const result = await submitOrder(recipientInfo, merchant, remarkMap);
      if (!result) return;
    }
    for (let i = 0; i < list.length; i += 1) {
      const order = list[i];
      await deleteOrder(order);
    }
  };
  const cancelOrder = async (outMergeNo: string) => {
    const response = await $api.getOrderSubmitMergeNoCancel(outMergeNo);
    switch (response.__error) {
      case undefined:
        return true;
      default:
        return false;
    }
  };
  const deleteOrder = async (order: OrderDetail) => {
    await $api.deleteOrderQueryId(order.out_trade_no);
  };
  const getTrialList = async (
    recipientInfo: RecipientInfo,
    merchant: OrderMerchantVO
  ) => {
    const response = await $api.postOrderSubmitTrial({
      order_req: merchant.detail_list.map((item) => ({
        sku_id: item.sku_id,
        quantity: item.quantity,
        discount_type: 'NONE',
        landing_page_id: item.spu_id,
        activity_id: item.activity_id,
        activity_type: item.activity_type
      })),
      recipient_info: recipientInfo
    });
    switch (response.__error) {
      case undefined:
        return response.data.list;
    }
  };
  const submitOrder = async (
    recipientInfo: RecipientInfo,
    merchant: OrderMerchantVO,
    remarkMap: Map<string, string>
  ) => {
    const detailList =
      merchant.detail_list.map((item) => ({
        ...item,
        landing_page_id: ''
      })) ?? [];
    const response = await $api.postOrderSubmitUpsert([
      {
        uid: merchant.uid,
        merchant_id: merchant.merchant_id,
        recipient_info: recipientInfo,
        detail_list: detailList,
        cart_list: [],
        customer_remark: remarkMap.get(merchant.uid) ?? '',
        landing_page_id: ''
      }
    ]);
    switch (response.__error) {
      case undefined:
        return true;
      default:
        return false;
    }
  };

  return { payOrder, cancelMergeOrder };
};
